package com.wash.shoes.controller.pc;

import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import javax.servlet.http.HttpServletRequest;

import com.ruoyi.common.enums.AccessoriesEnum;
import com.ruoyi.common.enums.RemarkEnum;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.lop.open.api.sdk.DefaultDomainApiClient;
import com.lop.open.api.sdk.LopException;
import com.lop.open.api.sdk.domain.ECAP.CommonCreateOrderApi.commonCheckPreCreateOrderV1.CommonCreateOrderRequest;
import com.lop.open.api.sdk.domain.ECAP.CommonCreateOrderApi.commonCheckPreCreateOrderV1.CommonProductInfo;
import com.lop.open.api.sdk.domain.ECAP.CommonCreateOrderApi.commonCheckPreCreateOrderV1.Contact;
import com.lop.open.api.sdk.plugin.LopPlugin;
import com.lop.open.api.sdk.plugin.factory.OAuth2PluginFactory;
import com.lop.open.api.sdk.request.ECAP.EcapV1OrdersPrecheckLopRequest;
import com.lop.open.api.sdk.response.ECAP.EcapV1OrdersPrecheckLopResponse;
import com.meituan.sdk.MeituanResponse;
import com.meituan.sdk.auth.MeituanTokenData;
import com.meituan.sdk.auth.MeituanTokenResponse;
import com.meituan.sdk.internal.exceptions.MtSdkException;
import com.meituan.sdk.model.ddzhkh.dingdan.orderQueryInfo.OrderQueryInfoRequest;
import com.meituan.sdk.model.ddzhkh.dingdan.orderQueryInfo.OrderQueryInfoResponse;
import com.meituan.sdk.model.ddzhkh.dingdan.orderQueryorder.OrderQueryorderRequest;
import com.meituan.sdk.model.ddzhkh.dingdan.orderQueryorder.OrderQueryorderResponse;
import com.ruoyi.common.core.domain.R;
import com.wash.shoes.common.enums.ChannelEnum;
import com.wash.shoes.common.property.JdProperty;
import com.wash.shoes.domain.mtbusy.MtAllClient;
import com.wash.shoes.entity.MtAuthPo;
import com.wash.shoes.entity.ShopPo;
import com.wash.shoes.oss.AliyunOSSUtil;
import com.wash.shoes.oss.ConstantProperties;
import com.wash.shoes.service.MtAuthService;
import com.wash.shoes.service.ShopService;
import com.wash.shoes.util.WashDateUtil;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.log4j.Log4j2;

/**
 * @author lijianguo
 * @Date 03/09/2024 请输入类的简介
 **/
@Log4j2
@Api(tags = {"PC-通用接口"})
@RequestMapping({"/common/", "/dev-api/common"})
@RestController
public class CommonNoAuthController {

    @Autowired
    JdProperty jdProperty;

    @Autowired
    MtAuthService mtAuthService;

    @Autowired
    ShopService shopService;

    @Autowired
    ConstantProperties constantProperties;

    @Autowired
    HttpServletRequest httpServletRequest;

    @ApiOperation("获取支持的渠道列表")
    @GetMapping("/getChannel")
    public R<List<Map>> getChannel() {
        return R.ok(Arrays.stream(ChannelEnum.values()).map(ChannelEnum::getMap).collect(Collectors.toList()));
    }

    @ApiOperation("上传图片")
    @PostMapping(value = "images/upload")
    R<String> uploadImages(@RequestPart(value = "file") MultipartFile multipartFile) throws IOException {
        return R.ok(AliyunOSSUtil.uploadMFile(multipartFile));
    }

    @ApiOperation("图片的前缀访问图片就需要前缀+url")
    @PostMapping(value = "imgPrefix")
    R<String> uploadImages() {
        return R.ok(ConstantProperties.BASEURL);
    }

    @ApiOperation("美团回调接口")
    @GetMapping(value = "mtCallBack")
    R<String> mtCallBack(String code, String sign, Long developerId, Integer businessId, String authorization_code) {
        try {
            String msgId = httpServletRequest.getParameter("msgId");
            log.info("美团回调打印消息的id,msgId为 [{}]", msgId);
        } catch (Exception e) {
            log.error("美团回调发生异常:{}", e.getMessage(), e);
        }
        log.info("mei tuan call black is  code[{}] sign[{}] developerId[{}] businessId[{}]", code, sign, developerId,
            businessId);
        log.info("mei tuan call black is  authorization_code[{}] ", authorization_code);
        MtAuthPo mtAuthPo = new MtAuthPo();
        mtAuthPo.setCode(code);
        mtAuthPo.setSign(sign);
        mtAuthPo.setDeveloperId(String.valueOf(developerId));
        mtAuthPo.setBusinessId(String.valueOf(businessId));
        try {
            log.info("zzz获取美团授权信息参数businessId: [{}], code: [{}]", businessId, code);
            MeituanTokenResponse meituanTokenResponse =
                MtAllClient.getClient(developerId).getOAuthToken(businessId, code);
            log.info("zzz获取美团授权信息结果 meituanTokenResponse: [{}]", meituanTokenResponse);
            mtAuthPo.setMtResponse(JSONObject.toJSONString(meituanTokenResponse));
            MeituanTokenData meituanTokenData = meituanTokenResponse.getData();
            mtAuthPo.setMtCode(String.valueOf(meituanTokenResponse.getCode()));
            mtAuthPo.setMtMsg(meituanTokenResponse.getMsg());
            // 保存美团的签名信息
            mtAuthPo.setAccessToken(meituanTokenData.getAccessToken());
            mtAuthPo.setExpireIn(String.valueOf(meituanTokenData.getExpireIn()));
            mtAuthPo.setRefreshToken(meituanTokenData.getRefreshToken());
            mtAuthPo.setScope(meituanTokenData.getScope());
            mtAuthPo.setOpBizCode(meituanTokenData.getOpBizCode());
            mtAuthPo.setOpBizName(meituanTokenData.getOpBizName());
            // 58是创建店铺,59是公司的授权
            ShopPo shopPo = shopService.getShopByName(meituanTokenData.getOpBizName());
            if (shopPo != null) {
                shopPo.setOpBizCode(meituanTokenData.getOpBizCode());
                shopPo.setAuthExpireDate(WashDateUtil.addSecond(meituanTokenData.getExpireIn()));
                shopService.updateById(shopPo);
                log.info("更新门店的授权成功 {}", JSONObject.toJSONString(shopPo));
            } else {
                log.error("门店更新失败，请检查门店是否存在");
                // 门店不存在,手动创建一个门店
                shopPo = new ShopPo();
                shopPo.setOpBizCode(meituanTokenData.getOpBizCode());
                shopPo.setAuthExpireDate(WashDateUtil.addSecond(meituanTokenData.getExpireIn()));
                shopPo.setShopName(meituanTokenData.getOpBizName());
                shopPo.setDeveloperId(String.valueOf(developerId));
                shopPo.setProvinces("51");
                shopPo.setCity("510104");
                shopPo.setCountry("5101");
                shopPo.setProvincesName("四川省");
                shopPo.setCityName("成都市");
                shopPo.setCountryName("锦江区");
                shopService.save(shopPo);
            }
            log.info("MeituanTokenResponse is {}", JSONObject.toJSONString(meituanTokenResponse));
        } catch (Exception e) {
            log.error(e);
            log.error("美团回调业务逻辑发生异常:{}", e.getMessage(), e);
            mtAuthPo.setMtMsg(e.getMessage());
        } finally {
            mtAuthService.save(mtAuthPo);
        }
        return R.ok("suc");
    }

    @ApiOperation("oss的配置信息")
    @GetMapping(value = "ossConfig")
    R<ConstantProperties> ossConfig() {
        return R.ok(constantProperties);
    }

    @ApiOperation("美团订单")
    @GetMapping(value = "mtOrderList")
    R<String> mtOrderList() throws MtSdkException {

        OrderQueryorderRequest orderQueryorderRequest = new OrderQueryorderRequest();
        orderQueryorderRequest.setPageNo(1);
        orderQueryorderRequest.setPageSize(10);
        orderQueryorderRequest.setOrderType(1);
        orderQueryorderRequest.setBuySuccessTimeFrom(System.currentTimeMillis() - 3600 * 1000 * 24 * 365);
        orderQueryorderRequest.setBuySuccessTimeTo(System.currentTimeMillis());
        String token =
            "V2-4927034280a6b5fa5ad19dd3ed7d3adf368de395d81388f2607748e27c9367c3d4e6911b1fe6447504e657cb40f65bbf659eeffc0d2989a72bed63765e51e4a825c5d9504fae880b96e5b9a3c963efe9";
        // meituanClient.getOAuthToken(59,"V2-bc6177b5b490126f84b4c583048addd85ac9342a97868ab4c71bed75c445a17b7f171846a418c5c67acbaaef448161de42b7ce7a7d39b8b25698f4bcf2b3aaf2f2544c15605b4294c2fd8b17349843968c3ec67ff746e727656cba6164e18e93");
        MeituanResponse<OrderQueryorderResponse> meituanResponse =
            MtAllClient.getClient("111").invokeApi(orderQueryorderRequest, token);
        OrderQueryorderResponse orderQueryorderResponse = meituanResponse.getData();
        log.info(JSONObject.toJSONString(orderQueryorderResponse));
        return R.ok("suc");
    }

    @ApiOperation("美团订单01")
    @GetMapping(value = "mtOrderList01")
    R<String> mtOrderList01() throws MtSdkException {

        // AliYunSmsUtil.sendSms("张白白","18382496398或18382496398","13880309055");

        return R.ok("suc");
    }

    @ApiOperation("美团订单02")
    @GetMapping(value = "mtOrderList02")
    R<String> mtOrderList02() throws MtSdkException {

        OrderQueryInfoRequest orderQueryorderRequest = new OrderQueryInfoRequest();
        orderQueryorderRequest.setOrderId("44381649");
        orderQueryorderRequest.setType(Arrays.asList(1));

        String token =
            "V2-4927034280a6b5fa5ad19dd3ed7d3adf368de395d81388f2607748e27c9367c3d4e6911b1fe6447504e657cb40f65bbf659eeffc0d2989a72bed63765e51e4a825c5d9504fae880b96e5b9a3c963efe9";
        // meituanClient.getOAuthToken(59,"V2-bc6177b5b490126f84b4c583048addd85ac9342a97868ab4c71bed75c445a17b7f171846a418c5c67acbaaef448161de42b7ce7a7d39b8b25698f4bcf2b3aaf2f2544c15605b4294c2fd8b17349843968c3ec67ff746e727656cba6164e18e93");
        MeituanResponse<OrderQueryInfoResponse> meituanResponse =
            MtAllClient.getClient("111").invokeApi(orderQueryorderRequest, token);
        OrderQueryInfoResponse orderQueryorderResponse = meituanResponse.getData();
        log.info(JSONObject.toJSONString(orderQueryorderResponse));
        return R.ok("suc");
    }

    @ApiOperation("jd test")
    @PostMapping(value = "images/test")
    R<String> test() throws IOException {

        // 示例为调用京东快递下单前置校验接口
        try {

            // 设置接口域名(有的对接方案同时支持生产和沙箱环境，有的仅支持生产，具体以对接方案中的【API文档-请求地址】为准)，生产域名：https://api.jdl.com
            // 预发环境域名：https://uat-api.jdl.com
            // DefaultDomainApiClient对象全局只需要创建一次
            DefaultDomainApiClient client = new DefaultDomainApiClient(jdProperty.getUrl(), 5000, 15000);

            // 入参对象（请记得更换为自己要使用的接口入参对象）
            EcapV1OrdersPrecheckLopRequest request = new EcapV1OrdersPrecheckLopRequest();

            // 设置入参（请记得更换为自己要使用的接口入参）
            Contact senderContact = new Contact();
            senderContact.setFullAddress("河北省廊坊市广阳区万庄镇中心小学");
            Contact receiverContact = new Contact();
            receiverContact.setFullAddress("拉萨市城关区康昂东路1-2号");
            CommonCreateOrderRequest requestDTO = new CommonCreateOrderRequest();
            requestDTO.setOrderOrigin(1);
            requestDTO.setCustomerCode(jdProperty.getCustomerCode());
            CommonProductInfo productInfo = new CommonProductInfo();
            productInfo.setProductCode("ed-m-0001");
            requestDTO.setProductsReq(productInfo);
            requestDTO.setReceiverContact(receiverContact);
            requestDTO.setSenderContact(senderContact);
            request.setRequest(requestDTO);

            System.out.println(JSON.toJSONString(request));

            // 设置插件，必须的操作，不同类型的应用入参不同，请看入参注释，公共参数按顺序分别为AppKey、AppSecret、AccessToken
            // 使用开放平台ISV/自研商家应用调用接口
            LopPlugin lopPlugin = OAuth2PluginFactory.produceLopPlugin(jdProperty.getAppKey(),
                jdProperty.getAppSecret(), jdProperty.getAccessToken());
            request.addLopPlugin(lopPlugin);

            EcapV1OrdersPrecheckLopResponse response = client.execute(request);
            System.out.println(response.getMsg());
        } catch (LopException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }

        return R.ok();
    }
    @GetMapping("/getAccessoriesEnums")
    @ApiOperation("获取支持的配饰枚举字典")
    public R<List> getAccessoriesEnums(){
        return R.ok(AccessoriesEnum.getList());
    }
    @GetMapping("/getRemarkEnums")
    @ApiOperation("备注枚举值枚举字典")
    public R<List> getRemarkEnums(){
        return R.ok(RemarkEnum.getList());
    }
}
